﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Logging;
using WebApp.Services;
using Newtonsoft.Json;



namespace WebApp.Controllers
{
    [Produces("application/json")]
    [Route("api/EfMySql")]
    public class EfMySqlController : Controller
    {


        private readonly ILogger<EfMySqlController> _logger;
        private readonly EfMySqlContextService _efMySqlContextService;

        public EfMySqlController(ILogger<EfMySqlController> logger, EfMySqlContextService efMySqlContextService)
        {
            _logger = logger;
            _efMySqlContextService = efMySqlContextService;
        }

        // GET api/values/id
        [HttpGet("{id}")]
        public string Get(int id)
        {
            var condition = _efMySqlContextService.TestModels.Where(c => c.Id == id);
            _logger.LogInformation("Get condition.ToSql()：" + condition.ToSql());

            string sql = "";
            VisitExpression(_efMySqlContextService, condition.Expression, ref sql);

            return JsonConvert.SerializeObject(condition.FirstOrDefault());

            //// 分页
            //var l = _sqlLiteContextService.TestModels.Where(c=>c.Id>2 && c.Id<5).OrderByDescending(c => c.Id)
            //    .Skip(1).Take(2);
            //return JsonConvert.SerializeObject(l.ToList());
        }






        // POST api/values
        [HttpPost]
        public string Post([FromBody]int key)
        {


            try
            {
                _efMySqlContextService.TestModels.Add(new TestModel { Name = DateTime.Now.ToShortTimeString() });

                var s = _efMySqlContextService.SaveChanges().ToString();
                _logger.LogInformation("_efMySqlContextService.SaveChanges().ToString()：" + s);

                return s;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "mysql 写入错误");
                return $"mysql 写入错误：{ex.Message}";
            }


        }






        public static void VisitExpression<T>(T enumerable, Expression expression, ref string sql)
        {
            if (sql == String.Empty)
                sql = GenerateSelectHeader(enumerable);
        }

        public static string GenerateSelectHeader<T>(T type)
        {
            var typeName = type.GetType().Name.Replace("\"", "");
            return string.Format("select * from {0} ", typeName);
        }








    }
}